package com.zzyl.common.ai;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class QianfanApiClient {
    @Autowired
    private QianfanApiClients qianfanApiClients;
    //构造器注入
    private final RestTemplate restTemplate;
    public QianfanApiClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String sendChatRequest(String prompt) {
          String apiUrl =qianfanApiClients.getApiUrl();
          String accessToken=qianfanApiClients.getAccessToken() ;
          String qianfanModel=qianfanApiClients.getQianfanModel();
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + accessToken);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", qianfanModel);

        // 构建messages列表
        List<Map<String, String>> messages = new ArrayList<>();

        // 添加user消息
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", prompt);
        messages.add(userMessage);

        requestBody.put("messages", messages);

        // 创建HttpEntity对象
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(
                apiUrl,
                requestEntity,
                String.class
        );

        if (response.getStatusCode().is2xxSuccessful()) {
            String json = response.getBody();
            JSONObject jsonObject = JSONUtil.parseObj(json);//将json转化成对象
            JSONArray choices = jsonObject.getJSONArray("choices");//将对象中的choices数组提取出来
            JSONObject choice = choices.getJSONObject(0);//数组中只有一个元素,因此采用索引0将其提取出来
            String str1 = choice.getJSONObject("message").getStr("content");//提取choices数组中message这个对象,提取对象中的content属性值
            return str1;
        } else {
            throw new RuntimeException("API请求失败: " + response.getStatusCode());
        }
    }

    // 使用示例
}